import telnetlib
from ping3 import ping
import logging
import socket
import os
import argparse
import time
import sys
import platform
if platform.system() == 'Windows':
    run_log = '../../run.txt'
elif platform.system() == 'linux':
    run_log = '/log/run.log'
else:
    run_log = 'run.txt'
if os.path.exists(run_log):
    os.remove(run_log)
logger = logging.getLogger()
logger.setLevel('DEBUG')
BASIC_FORMAT = "%(asctime)s :%(levelname)s :%(message)s"
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
chlr = logging.StreamHandler() # 输出到控制台的handler
chlr.setFormatter(formatter)
chlr.setLevel('DEBUG')  # 也可以不设置，不设置就默认用logger的level
fhlr = logging.FileHandler(run_log) # 输出到文件的handler
fhlr.setFormatter(formatter)
logger.addHandler(chlr)
logger.addHandler(fhlr)

##telnet访问函数
def to_up(Host, port, timeout, frequency):
    info = ("第[%s]次访问地址[%s:%s]" %(frequency, Host, port))
    try:
        tn = telnetlib.Telnet(Host, port=port, timeout=timeout)
        tn.close()
        de = info + "成功\n"
        logger.debug(de)
    except:
        err = info + "失败\n"
        logger.error(err)
#测试功能类    
class Test:
    def __init__(self, frequency, port, timeout, host):
        self.frequency = frequency
        self.host = host
        self.port = int(port)
        self.timeout = int(timeout)
    def pings(self):
        for s in range(1, self.frequency):
            res = ping(dest_addr=str(self.host), timeout=int(self.timeout))
            if res == 'False':
                logger.error("对主机[%s]进行第[%s]次[ping]检测失败\n" % (self.host, s))
            else:
                logger.info("对主机[%s]进行第[%s]次[ping]检测成功\n" % (self.host, s))
    def telnet(self):
        end = int(self.frequency) + 1
        for s in range(1, end):
            to_up(Host=self.host, port=self.port, timeout=self.timeout, frequency=s)
    def socket(self):
        s = socket.socket() ##实例化
        s.settimeout(self.timeout) ##设置超时时间
        logger.info("正在进行[socket]测试,连接--->>[%s:%s]中\n" % (self.host, self.port)) #打印当前测试信息
        end = int(self.frequency) + 1
        for ss in range(1, end):
            try:
                s.connect((self.host, self.port)) #开始进行测试
                logger.info("第[%s]次测试->连接[%s:%s]成功\n" % (ss, self.host, self.port))
            except:
                logger.error("第[%s]次测试->连接[%s:%s]失败\n" % (ss, self.host, self.port))
            time.sleep(self.timeout)
            s.close()
#获取程序信息    
def get_info(url_file, types, frequency=1, timeout=None):
    if os.path.exists(url_file):
        # 打开文件
        file = open(url_file, "r", encoding='utf-8')
        # # 遍历文件行内容
        for (num, line) in enumerate(file, 1):
            line = str.replace(line, '\n', '')
            logger.info("正在检测第[%s]行内容:[%s]" % (num, line))
            xi2 = [line]
            up_time = time.time()
            for i in xi2:
                domain_port = i.split(' ')
                domain = domain_port[0]
                port = domain_port[1]
                logger.info("第[%s]行获取的地址：[%s]" % (num, domain))
                logger.info("第[%s]行获取的端口：[%s]\n" % (num, port))
                logger.info("正在对[%s:%s]进行[%s]检测" % (domain, port, types))
                Program = Test(frequency=frequency, port=port, timeout=timeout, host=domain)
                if types == 'telnet':
                    Program.telnet()
                elif types == 'socket':
                    Program.socket()
                elif types == 'ping':
                    Program.pings()
                else:
                    logger.error("传入的测试[%s]不属于本程序功能，请重新传入\t可选:[telnet/ping/socket]" %types)
        end_time = time.time()
        times = end_time - up_time
        logger.info("本次进行[%s]测试,共耗时[%s]秒" % (types, times))
        file.close()
    else:
        logger.error("找不到文件[%s]" %url_file)
        exit("程序终止")


if sys.argv[1] == '-h':
    p = argparse.ArgumentParser()
    p.add_argument('p', help='帮助信息', metavar='参数')
    ddata = {'-f': {'--file': '[必选]指定一个存放IP/域名及端口的文本文件,例如[ -f lixt.txt ]，文本格式:[IP PORT]'},
             '-n': {'--frequency': '[必选]设置单个IP的测试次数,该参数值为整型,例如[ -n 4 ]'},
             '-T': {'--type': '[必选]设置测试类型，多选一:[telnet/socket/ping],例如[ -T telnet ]'},
             '-time': {'--time':'[可选]设置请求超时时间,默认[5]秒,例如 [ -time 10 ]'},
             '-I': {'--Interval_time':'[可选]设置单次测试间隔时间,默认[1]秒,例如 [ -I 10 ]'},
             '-l': {'--log': '自定义日志文件,命令模板: [ -l /opt/run.log ]'},
             }
    for i in ddata:
        parameter = i
        s = ddata[i]
        for si in s:
            parameters = si
            describe = s[si]
            p.add_argument(i, help=describe, nargs=1, metavar=parameters)
    args = p.parse_args()
    print(args.p)
else:
    ##接收参数
    must = argparse.ArgumentParser(description="设置参数")
    musts = {'-f': {'--file': 'list.txt'}, '-n': {'--frequency': '3'}, '-T': {'--type': 'socket'}}
    for i in musts:
        parameter = i
        s = musts[i]
        for si in s:
            parameters = si
            default = s.get(si)
            must.add_argument(parameter, parameters, required=True, default=default)
    must.add_argument('-time', '--time', required=False, default=1)
    must_all = must.parse_args()
    file = must_all.file
    frequency = int(must_all.frequency)
    type = must_all.type
    times = int(must_all.time)
    logger.info("传入的参数如下:\n[文件]:[%s]\n[测试次数]:[%s]\n[测试类型]:[%s]\n" % (file, frequency, type))
    logger.debug("可选参数配置如下:\n[连接超时时间]:[%s]秒\n" % times)

    #开始传入测试参数
    get_info(url_file=file, types=type, frequency=frequency, timeout=times)
    logger.debug("本次程序运行日志已存至[%s]文件" %run_log)